package com.Ruier.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.UUID;

@Component
public class Uploadfile {
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private String accessKeyId = "LTAI5tLDyv3DVstBmd8tCQto";
    private String accessKeySecret = "SgS8UeB3XimpzFg1JlwiIvNGLYEiGY";
    // 填写Bucket名称，例如examplebucket。
    private String bucketName = "web-tails-ruier";

    public String upload(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();

        String originalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID()+ originalFilename.substring(originalFilename.lastIndexOf("."));

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName,filename,inputStream);
        String url=endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+filename;
        ossClient.shutdown();
        return url;
    }
}
